﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Windows.Forms;
using System.Net;
using HtmlAgilityPack;


namespace Homework_8
{
    public partial class Form1 : Form
    {
        string searchText = "";
        public Form1()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
        }
        
        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(textBox1.Text))
                {
                    richTextBox1.Text = "请先输入检索内容";
                }
                else
                {
                    searchText = textBox1.Text;
                    //百度url
                    string url_baidu = getURL(searchText, 0);
                    //BingUrl
                    string url_bing = getURL(searchText, 1);
                    //获取知乎0-400字符并输出
                    Task showZhiHu=Task.Run(()=>{
                        richTextBox1.Text = getText(url_baidu, 0, 400);
                    });
                    //获取bing0-400字符并输出
                    Task showBing = Task.Run(() =>
                    {
                        richTextBox2.Text = getText(url_bing, 0, 400);
                    });
                    Task.WaitAll(showZhiHu, showBing);

                }
            }
            catch (Exception ex)
            {
                richTextBox1.Text = ex.ToString();
            }
        }

        //获取网址
        private string getURL(string searchText,int type) 
        {
            string url = "";
            switch (type)
            {
                case 0:url = "https://www.zhihu.com/search?type=content&q=" + searchText;
                    break;
                case 1:url = "https://cn.bing.com/search?q=" + searchText;
                    break;
                    //默认百度
                default:
                    url = "https://www.baidu.com/s?wd=" + searchText;
                    break;
            }
            return url;
        }
        //单个搜索获取文本
        private string getText(string url,int start,int end)
        {
            string result = "";
            //获取html
            WebClient client = new WebClient();
            client.Encoding = Encoding.UTF8;
            string html = client.DownloadString(url);
            //将网页内容加载到HtmlDocument
            HtmlAgilityPack.HtmlDocument doc =new HtmlAgilityPack.HtmlDocument();
            doc.LoadHtml(html);
            //获取body节点
            HtmlNode body = doc.DocumentNode.SelectSingleNode("//body");
            //获取body元素start到end字符的文本内容
            result = body.InnerText.Substring(start, end);
            return result;
        }

       
    }
}




